package org.learn.phase3.socket;
//客户端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class SocketTCP01Client {
    public static void main(String[] args) throws IOException {
        //1.连接服务器（IP，端口）
        //连接本机的9999端口
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("客户端 socket = " + socket.getClass());
        //2.连接上后，生成Socket，通过Socket.getOutputStream()得到和socket对象关联的输出流对象
        OutputStream outputStream = socket.getOutputStream();
        //3.通过输出流，写入数据到数据通道；
//        字节流outputStream.write("hello,server".getBytes());
        //使用字符流
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello,server 字符流");
        bufferedWriter.newLine();//插入一个换行，表示写入内容结束，但是要求对方使用readLine（）！！！
        bufferedWriter.flush();//写入字符流需要手动刷新，否则数据不会写入数据通道


        //写入结束标记
        socket.shutdownOutput();
        //4.获取和socket 关联的输出流，读取数据，并显示
        InputStream inputStream = socket.getInputStream();
//        byte[] buf = new byte[1024];
//        int readLine = 0;
//        while ((readLine = inputStream.read(buf)) != -1){
//            System.out.println(new String(buf,0,readLine));
//        }

        //使用字符流接收
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String x = bufferedReader.readLine();
        System.out.println(x);

        //5.关闭流对象和socket ，必须关闭！！！
        bufferedReader.close();
        inputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("客户端退出。。。。。");
    }
}
